package com.daniel.cms.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;

/**
 * Token处理类
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/4/20 17:37
 */
public class JwtUtil {

	/**
	 * 过期时间为一天
	 */
	private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

	/**
	 * token私钥
	 */
	private static final String TOKEN_SECRET = "daniel_cms_token_secret";

	/**
	 * AUTH
	 */
	private static final String AUTH = "auth0";

	/**
	 * 生成签名,15分钟后过期
	 *
	 * @param userName 用户名
	 * @param userId   用户编号
	 * @return 签名信息token
	 */
	public static String sign(String userName, String userId) {
		//过期时间
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		//私钥及加密算法
		Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
		//设置头信息
		HashMap<String, Object> header = new HashMap<>(2);
		header.put("typ", "JWT");
		header.put("alg", "HS256");
		//附带username和userID生成签名
		return JWT.create()
				.withHeader(header)
				.withIssuer(AUTH)
				.withClaim("account", userName)
				.withClaim("code", userId)
				.withExpiresAt(date)
				.sign(algorithm);
	}

	/**
	 * 获取用户编号
	 *
	 * @param token token
	 * @return 用户编号
	 */
	public static String getUserCode(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).withIssuer(AUTH).build();
			DecodedJWT jwt = verifier.verify(token);
			if (jwt != null) {
				return jwt.getClaim("code").asString();
			}
			return null;
		} catch (IllegalArgumentException | JWTVerificationException e) {
			return null;
		}
	}

	/**
	 * 验证token
	 *
	 * @param token token
	 * @return 是否验证通过
	 */
	public static boolean verity(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).withIssuer(AUTH).build();
			DecodedJWT jwt = verifier.verify(token);
			// System.out.println("认证通过：");
			// System.out.println("issuer: " + jwt.getIssuer());
			// System.out.println("code: " + jwt.getClaim("code").asString());
			// System.out.println("account: " + jwt.getClaim("account").asString());
			// System.out.println("过期时间：      " + jwt.getExpiresAt());
			return true;
		} catch (IllegalArgumentException | JWTVerificationException e) {
			return false;
		}
	}
}

